package ecommerce.action;

import org.apache.log4j.Logger;

import ecommerce.dao.TagDAOImpl;
import ecommerce.dao.UserDAOImpl;
import ecommerce.dao.UserTagDAOImpl;
import ecommerce.model.*;
import com.opensymphony.xwork2.*;

import java.io.*;
import java.net.*;
import java.util.*;

import javax.servlet.http.*;
import javax.xml.parsers.*;

import org.apache.struts2.ServletActionContext;
import org.w3c.dom.*;

public class MembersAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(MembersAction.class);
	
	private String keyword = null;
	private String sortBy = null;
	List<Photo> photoBeans = null;
	private int maxPage = 5;
	
	public String membersPage() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("currentPage", 0);
		return SUCCESS;
	}	
		
	public String searchPhoto(){
		System.setProperty("http.proxyHost", "www-cache.usyd.edu.au");
		System.setProperty("http.proxyPort","8080");
		HttpServletRequest request = ServletActionContext.getRequest();
		setKeyword(request.getParameter("keyword"));
		setSortBy(request.getParameter("sortBy"));
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("currentPage", 1);
		if(getFlickrPhotos() && readFlickrPhotos(1))
		{
			if(sessionValidation()){
				new UserDAOImpl().updateQueriesSubmitted((int)((Integer)session.get("current_user")));
			}
		}
		else if(sessionValidation())
		{
			logger.error("Error on calling Flickr web services");
			addFieldError("keyword", "Error on calling Flickr web services");			
		}
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String searchResult()
	{
	    Map<String, Object> session = ActionContext.getContext().getSession();
	    photoBeans = (List<Photo>)session.get("searchResult");
	    session.remove("searchResult");
		return SUCCESS;
	}
	
	public boolean getTopTenTags()
	{
		Map<String, Object> session = ActionContext.getContext().getSession();
		List<UserTag> topTenTags = new UserTagDAOImpl().getTopTenUserTag((int)((Integer)session.get("current_user")));
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset = UTF-8");  
		response.setHeader("Cache - Control", "no - cache"); 
		try
		{
			PrintWriter printWriter = response.getWriter();  
			StringBuffer sb = new StringBuffer("");
			if(topTenTags != null && topTenTags.size() > 0)
			{
				sb.append("<table class=\"data_table\">");   
	            sb.append("<tr><th>Tag</th><th>Frequency</th></tr>");
	            for(int i = 0; i < topTenTags.size(); i++)
	            {
	            	sb.append("<tr class=\"" + (i%2 == 0 ? "filed_nobg" : "field_bg") + "\">");
	            	sb.append("<td class=\"tag\">" + new TagDAOImpl().getTagById(topTenTags.get(i).getTagId()).getTagDescription() 
	            			+ "</td> <td class=\"frequency\">" + topTenTags.get(i).getFrequency() + "</td>");
	            	sb.append("</tr>");
	            }
	            sb.append("</table>");  
			}
			else
			{
				sb.append("<p class=\"noTopTenTags\"> No Tags Recorded </p>");   
			}
            printWriter.print(sb.toString());  
            printWriter.close();  
            printWriter = null; 
			return true;
        }  
        catch (IOException e)  
        {  
        	logger.error("Error on retrieving top ten tags: " + e);  
            return false;
        }  
	}
	
	@SuppressWarnings("unchecked")
	public boolean sessionValidation()
	{
		Map<String, Object> session = ActionContext.getContext().getSession();
		List<String> tagList = ((List<String>)session.get("tagList")) != null 
									? ((List<String>)session.get("tagList")) 
							        : new ArrayList<String>();
		if(!tagList.contains(keyword))
		{
			tagList.add(keyword);
			session.put("tagList", tagList);
			return true;
		}
		return false;
	}
	
	public boolean getFlickrPhotos(){
		String urlString = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=deccef4c74921a3797eac78eebd5c457&tags=<tags>&sort=<sort>&per_page=100&page=1";
		try{
			urlString = urlString.replace("<tags>", URLEncoder.encode(keyword,"UTF-8"));
			urlString = urlString.replace("<sort>", sortBy.toLowerCase());
			
			URL url = new URL(urlString);  
			URLConnection urlConnection = url.openConnection();  
			urlConnection.setConnectTimeout(120000);  
			urlConnection.setReadTimeout(120000);  
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
	        String line=null;  
	        StringBuffer sb = new StringBuffer();
	        while ( (line = reader.readLine()) != null ) {  
	        	sb.append(line);
	        	sb.append("\n");
	        }         
	        reader.close(); 
	        
	        File file = new File("U:\\tempFile_userid.xml");
	        PrintWriter pw = new PrintWriter(new OutputStreamWriter
                    (new FileOutputStream(file),"UTF8"));
	        pw.println(sb.toString());
	        pw.close();
	        return true;
		}
		catch(Exception e)
		{
			logger.error("Error on getting Flickr data " + e);
			return false;
		}
	}
	
	public String setPageNumber(){
		try
		{
			Map<String, Object> params = ActionContext.getContext().getParameters();
			Map<String, Object> session = ActionContext.getContext().getSession();
		    session.put("currentPage", Integer.parseInt(((String[])params.get("page"))[0]));
			readFlickrPhotos(Integer.parseInt(((String[])params.get("page"))[0]));
		}
		catch(Exception e)
		{
			logger.error("Error on reading search result " + e);
			addFieldError("keyword", "Error on calling Flickr web services");
		}
		return SUCCESS;
	}
	
	public boolean readFlickrPhotos(int pageNumber){
		photoBeans = new ArrayList<Photo>();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse("U:\\tempFile_userid.xml");
		    NodeList nl = doc.getElementsByTagName("photo");
		    for(int i = ((pageNumber-1)*20); i < (pageNumber*20); i++)
		    {
			    Element a = (Element)nl.item(i);
			    photoBeans.add(new Photo(a.getAttribute("farm"), a.getAttribute("server"),
			    		a.getAttribute("id"), a.getAttribute("owner"), a.getAttribute("secret")));
		    }
		    Map<String, Object> session = ActionContext.getContext().getSession();
		    session.put("searchResult", photoBeans);
		    return true;
		} 
		catch (Exception e)
		{
			logger.error("Error on calling Flickr web services " + e);
			addFieldError("photoBean.keyword", "Error on calling Flickr web services");
			return false;
		}    	    
	}
	
	public void setKeyword(String keyword)
	{
	    this.keyword=keyword;
	}

    public String getKeyword()
    {
    	return this.keyword;
    }
    
	public void setPhotoBeans(List<Photo> photoBeans)
	{
	    this.photoBeans=photoBeans;
	}

    public List<Photo> getPhotoBeans()
    {
    	return this.photoBeans;
    }
    
	public void setSortBy(String sortBy)
	{
	    this.sortBy = (sortBy.equals("2")
	    			   ? "interestingness-desc"
	    		       : "relevance");
	}
	
    public String getSortBy()
    {
    	return this.sortBy;
    }
    
    public int getMaxPage()
    {
    	return this.maxPage;
    }
    
	public void setMaxPage(int maxPage)
	{
	    this.maxPage=maxPage;
	}
}
